﻿using System;
using System.Linq;
using System.Web.Security;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Web;
namespace AzureHelpers
{
    public class FirstRequestInitialization
    {
        private static bool s_InitializedAlready = false;
        private static Object s_lock = new Object();

        public static void Initialize(string adminName)
        {
            if (s_InitializedAlready)
            {
                return;
            }
            lock (s_lock)
            {
                if (s_InitializedAlready)
                {
                    return;
                }

                ApplicationStartUponFirstRequest(null, adminName);
                s_InitializedAlready = true;
            }
        }

        private static void ApplicationStartUponFirstRequest(HttpContext context, string adminName)
        {
            // This is where you put initialization logic for the site.
            // RoleManager is properly initialized at this point.

            if (!Roles.RoleExists("Administrators")) Roles.CreateRole("Administrators");
            //if (!Roles.RoleExists("Friends")) Roles.CreateRole("Friends");
            //TODO: remove this from real production
            if (Membership.GetUser(adminName) != null)
            {
                Membership.DeleteUser(adminName);
            }
            if (Membership.GetUser(adminName) == null)
            {
                Membership.CreateUser(adminName, adminName, "myemail@email.com");
                Roles.AddUserToRole(adminName, "Administrators");
            }

            

            if (RoleEnvironment.IsAvailable)
            {
                // Restart the role upon all configuration setting changes
                RoleEnvironment.Changing += (sender, e) => { if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange)) e.Cancel = true; };
            }
        }
    }
}